package com.niiwoo.civet.mobile.controller.creditor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.mobile.vo.request.creditor.InvestOrderIdsRequestVO;
import com.niiwoo.civet.mobile.vo.request.creditor.TradableInvestOrderPageRequestVO;
import com.niiwoo.civet.mobile.vo.request.creditor.TradableInvestOrderRequestVO;
import com.niiwoo.civet.mobile.vo.response.creditor.InvestOrderTradableValidateResponseVO;
import com.niiwoo.civet.mobile.vo.response.creditor.TradableInvestOrderListResponseVO;
import com.niiwoo.civet.mobile.vo.response.creditor.TradableInvestOrderTotalMoneyResponseVO;
import com.niiwoo.civet.mobile.vo.response.creditor.TradableInvestOrderVO;
import com.niiwoo.civet.mobile.vo.response.user.UserBasicDataResponseVO;
import com.niiwoo.civet.trade.dto.common.PeriodDTO;
import com.niiwoo.civet.trade.dto.common.ProjectRatePeriodDTO;
import com.niiwoo.civet.trade.dto.request.creditor.InvestOrderTradableValidateRequestDTO;
import com.niiwoo.civet.trade.dto.request.creditor.TradableInvestOrderRequestDTO;
import com.niiwoo.civet.trade.dto.response.creditor.InvestOrderTradableValidateResponseDTO;
import com.niiwoo.civet.trade.dto.response.creditor.PageTradableInvestOrderDTO;
import com.niiwoo.civet.trade.dto.response.creditor.TradableInvestOrderDTO;
import com.niiwoo.civet.trade.dto.response.creditor.TradableInvestOrderStatDTO;
import com.niiwoo.civet.trade.service.creditor.TradableInvestOrderDubboService;
import com.niiwoo.civet.user.dto.request.SimpleOrgInfo;
import com.niiwoo.civet.user.dto.response.UserBasicInfoDTO;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.civet.user.service.UserBasicInfoDubboService;
import com.niiwoo.tripod.web.util.PrincipalContext;
import com.niiwoo.tripod.web.vo.Result;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/investOrder")
@Api(tags = "V5.4.0可交易债权", description = "/investOrder")
@Slf4j
public class TradableInvestOrderController {
	
	@Reference(version = "1.0.0")
    private UserBasicInfoDubboService userBasicInfoDubboService;
	
	@Reference(version = "1.0.0")
    private OrganizationDubboService organizationDubboService;
	
	@Reference(version = "1.0.0")
    private TradableInvestOrderDubboService tradableInvestOrderDubboService;
	
	@PostMapping("/tradable/list")
    @ApiOperation("V5.4.0可交易债权列表——分页列表")
    public Result<TradableInvestOrderListResponseVO> getAllTradableInvestOrdersByPage(@RequestBody @Valid TradableInvestOrderPageRequestVO request) {
		String userId = PrincipalContext.getUserId();
		log.info("可交易的投资订单列表,请求参数={}", request);
		
		TradableInvestOrderRequestDTO requestDto = new TradableInvestOrderRequestDTO();
		requestDto.setPageNumber(request.getPageNumber());
		requestDto.setPageSize(request.getPageSize());
		requestDto.setSort(request.getSort());
		requestDto.setSortType(request.getSortType());
		requestDto.setUserId(userId);
		requestDto.setLoanType(request.getLoanType());
		requestDto.setRate(request.getInterestRate());
		if (request.getRepaymentTypes() != null && !"".equals(request.getRepaymentTypes())) {
			List<Byte> repaymentTypes = new ArrayList<Byte>();
			for (String s : Arrays.asList(request.getRepaymentTypes().split(","))) {
				repaymentTypes.add(Byte.valueOf(s));
			}
			requestDto.setRepaymentTypes(repaymentTypes);
		}
		// V5.3.0
//		if (request.getProjectTypes() != null && !"".equals(request.getProjectTypes())) {
//			List<Byte> projectTypes = new ArrayList<Byte>();
//			for (String s : Arrays.asList(request.getProjectTypes().split(","))) {
//				projectTypes.add(Byte.valueOf(s));
//			}
//			requestDto.setProjectTypes(projectTypes);
//		}
//		if (request.getCreditType() != null) {
//			List<Byte> creditTypes = new ArrayList<>();
//			switch (request.getCreditType()) {
//			case 1: //1-社保授信
//			case 7: //7-信用卡授信
//			case 8: //8-房产授信
//				creditTypes.add(request.getCreditType());
//				break;
//			case 11: //信用授信
//				creditTypes.add(request.getCreditType()); //11-信用授信
//				creditTypes.add((byte) 5); //5-自由资产
//				creditTypes.add((byte) 6); //6-融360自有资产
//				break;
//			}
//			
//			requestDto.setCreditTypes(creditTypes);
//		}
//		if (request.getRateCondition() != null) {
//			ProjectRatePeriodDTO p = new ProjectRatePeriodDTO(request.getRateCondition().getBegin(), request.getRateCondition().getEnd());
//			p.setBeginQueryType(request.getRateCondition().getBeginQueryType());
//			p.setEndQueryType(request.getRateCondition().getEndQueryType());
//			requestDto.setRateDto(p);
//		}
		if (request.getPeriodCondition() != null) {
			PeriodDTO p = new PeriodDTO((byte)1, request.getPeriodCondition().getBegin(), request.getPeriodCondition().getEnd());
			p.setBeginQueryType(request.getPeriodCondition().getBeginQueryType());
			p.setEndQueryType(request.getPeriodCondition().getEndQueryType());
			requestDto.setPeriodDto(p);
		}
		
		PageTradableInvestOrderDTO pageRecords = tradableInvestOrderDubboService.getAllTradableInvestOrders(requestDto);
		List<TradableInvestOrderDTO> list = pageRecords.getItems();
        
        TradableInvestOrderListResponseVO resultVO = new TradableInvestOrderListResponseVO();
        if (list != null && !list.isEmpty()) {
        	List<TradableInvestOrderVO> tradableInvestOrderVOs = new ArrayList<>();
        	
        	//获取对应借款人信息
        	Set<String> userIdSet = new HashSet<>();
        	for (TradableInvestOrderDTO dto : list) {
        		userIdSet.add(dto.getBorrowUserId());
        	}
        	Map<String, UserBasicInfoDTO> userMap = new HashMap<>();
        	if (!userIdSet.isEmpty()) {
	        	List<UserBasicInfoDTO> userBasicInfoDTOS = userBasicInfoDubboService.queryListByUserIdSet(userIdSet);
	        	for (UserBasicInfoDTO user : userBasicInfoDTOS) {
	        		userMap.put(user.getUserId(), user);
	        	}
        	}
        	
        	Set<String> orgInfoIdSet = new HashSet<>();
        	for (TradableInvestOrderDTO dto : list) {
        		if (userMap.containsKey(dto.getBorrowUserId())) continue;
        		
        		orgInfoIdSet.add(dto.getBorrowUserId());
        	}
        	Map<String, SimpleOrgInfo> orgMap = new HashMap<>();
        	if (!orgInfoIdSet.isEmpty()) {
	        	List<SimpleOrgInfo> orgInfoDTOS = organizationDubboService.queryListByOrgIdSet(orgInfoIdSet);
	        	for (SimpleOrgInfo org : orgInfoDTOS) {
	        		orgMap.put(org.getId(), org);
	        	}
        	}

        	TradableInvestOrderVO vo = null;
        	for (TradableInvestOrderDTO dto : list) {
        		vo = new TradableInvestOrderVO();
        		
        		BeanUtils.copyProperties(dto, vo);
        		
        		vo.setIsOrgProject(0);
        		
        		// 封装返回的用户信息
        		UserBasicInfoDTO userBasicInfoResponseDTO = userMap.get(dto.getBorrowUserId());
    	        if(userBasicInfoResponseDTO != null){
    	        	UserBasicDataResponseVO userBasicDataResponseVO = new UserBasicDataResponseVO();
    	            userBasicDataResponseVO.setUserId(userBasicInfoResponseDTO.getUserId());
    	            userBasicDataResponseVO.setNickName(userBasicInfoResponseDTO.getNickName());
    	            userBasicDataResponseVO.setNiiwooCode(userBasicInfoResponseDTO.getNiiwooCode());
    	            userBasicDataResponseVO.setNiiwooScore(userBasicInfoResponseDTO.getNiiwooScore());
    	            userBasicDataResponseVO.setHeadImage(userBasicInfoResponseDTO.getHeadImage());
    	            
    	            vo.setUser(userBasicDataResponseVO);
    	        } else { //机构标
    	        	SimpleOrgInfo org = orgMap.get(dto.getBorrowUserId());
    	        	if (org != null) {
    	        		UserBasicDataResponseVO userBasicDataResponseVO = new UserBasicDataResponseVO();
        	            userBasicDataResponseVO.setUserId(org.getId());
        	            userBasicDataResponseVO.setNickName(org.getOrganizationName());
        	            
        	            vo.setUser(userBasicDataResponseVO);
        	            
        	            vo.setIsOrgProject(1);
    	        	}
    	        }
        		
        		tradableInvestOrderVOs.add(vo);
        	}
        	
        	resultVO.setItems(tradableInvestOrderVOs);
        }
        
        resultVO.setTotalCount(pageRecords.getTotalCount());
        resultVO.setTotalPage(pageRecords.getTotalPage());
        resultVO.setMaxSelect(pageRecords.getMaxSelect());
		
        return Result.with(resultVO);
    }
	
	@PostMapping("/tradable/detail")
    @ApiOperation("V5.3.0可交易债权详情")
    public Result<TradableInvestOrderVO> getTradableInvestOrder(@RequestBody @Valid TradableInvestOrderRequestVO request) {
		String userId = PrincipalContext.getUserId();
		
		TradableInvestOrderDTO dto = tradableInvestOrderDubboService.getTradableInvestOrder(userId, request.getInvestOrderId());

		TradableInvestOrderVO resultVO = new TradableInvestOrderVO();
		if (dto != null) {
			BeanUtils.copyProperties(dto, resultVO);
			
			resultVO.setIsOrgProject(0);
			
			Set<String> userIdSet = new HashSet<>();
    		userIdSet.add(dto.getBorrowUserId());
        	List<UserBasicInfoDTO> userBasicInfoDTOS = userBasicInfoDubboService.queryListByUserIdSet(userIdSet);
        	UserBasicInfoDTO userBasicInfoDTO = null;
        	if (userBasicInfoDTOS != null && !userBasicInfoDTOS.isEmpty()) userBasicInfoDTO = userBasicInfoDTOS.get(0);
        	
			UserBasicDataResponseVO userBasicDataResponseVO = new UserBasicDataResponseVO();
	        if(userBasicInfoDTO != null){
	            userBasicDataResponseVO.setUserId(userBasicInfoDTO.getUserId());
	            userBasicDataResponseVO.setNickName(userBasicInfoDTO.getNickName());
	            userBasicDataResponseVO.setNiiwooCode(userBasicInfoDTO.getNiiwooCode());
	            userBasicDataResponseVO.setNiiwooScore(userBasicInfoDTO.getNiiwooScore());
	            userBasicDataResponseVO.setHeadImage(userBasicInfoDTO.getHeadImage());
	        } else { //机构标
	        	SimpleOrgInfo org = organizationDubboService.getByOrgId(dto.getBorrowUserId());
	        	if (org != null) {
    	            userBasicDataResponseVO.setUserId(org.getId());
    	            userBasicDataResponseVO.setNickName(org.getOrganizationName());

    	            resultVO.setIsOrgProject(1);
	        	}
	        }
	        
	        resultVO.setUser(userBasicDataResponseVO);
		}
		
        return Result.with(resultVO);
    }
	
	@PostMapping("/tradable/totalmoney")
    @ApiOperation("V5.3.0可交易债权总金额")
    public Result<TradableInvestOrderTotalMoneyResponseVO> getTradableInvestOrderTotalMoney() {
		String userId = PrincipalContext.getUserId();
		
		TradableInvestOrderStatDTO dto = tradableInvestOrderDubboService.getTradableInvestOrderStat(userId);
		
		TradableInvestOrderTotalMoneyResponseVO resultVO = new TradableInvestOrderTotalMoneyResponseVO();
		if (dto != null) {
			BeanUtils.copyProperties(dto, resultVO);
		}
		
        return Result.with(resultVO);
    }
	
	@PostMapping("/tradable/validate")
    @ApiOperation("V5.3.0 债权是否可以转让校验")
    public Result<InvestOrderTradableValidateResponseVO> investOrderTradableValidate(@RequestBody @Valid InvestOrderIdsRequestVO requestVO) {
		InvestOrderTradableValidateResponseVO result = new InvestOrderTradableValidateResponseVO();
		
		InvestOrderTradableValidateRequestDTO request = new InvestOrderTradableValidateRequestDTO();
		request.setUserId(PrincipalContext.getUserId());
		request.setInvestOrderIds(requestVO.getInvestOrderIds());
		
		InvestOrderTradableValidateResponseDTO dto = tradableInvestOrderDubboService.investOrderTradableValidate(request);
		if (dto != null) {
			BeanUtils.copyProperties(dto, result);
		}
		
        return Result.with(result);
    }

}
